{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-1"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import cv2\n",
    "import numpy as np\n",
    "import random\n",
    "import math\n",
    "# 实质：卷积运算。先进行灰度转换然后使用高斯滤波去除噪声再调用OpenCV中的canny方法实现边缘检测\n",
    "img = cv2.imread('image0.jpg',1)\n",
    "imgInfo = img.shape\n",
    "height = imgInfo[0]\n",
    "width = imgInfo[1]\n",
    "cv2.imshow('img',img)\n",
    "# 1.灰度处理\n",
    "gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n",
    "# 2.高斯滤波进行平滑处理去除噪声\n",
    "imgGaussianFilter = cv2.GaussianBlur(gray,(3,3),0)\n",
    "# 调用canny方法,该方法只能处理灰度图\n",
    "dstImg = cv2.Canny(img,50,50)\n",
    "cv2.imshow('dstImg',dstImg)\n",
    "cv2.waitKey(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "源码实现边缘检测\n",
    "sobel1算子模板(左为竖直算子，右为水平算子)\n",
    "[ 1 2 1       [ 1 0 -1\n",
    "  0 0 0         2 0 -2\n",
    "-1 -2 -1]       1 0 -1 ]\n",
    "图片卷积运算\n",
    "[1 2 3 4]*[a b c d ]=a*1+b*2+c*3+d*4 = dstImg\n",
    "边缘判断：a为竖直方向上的卷积计算结果(竖直梯度) b为水平方向上卷积计算的结果(水平梯度) \n",
    "sqrt为开方 th为阈值，大于th则为边缘\n",
    "sqrt(a*a+b*b) > th\n",
    "'''\n",
    "img = cv2.imread('image0.jpg',1)\n",
    "imgInfo = img.shape\n",
    "height = imgInfo[0]\n",
    "width = imgInfo[1]\n",
    "# cv2.imshow('img',img)\n",
    "# 1.灰度处理\n",
    "gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n",
    "dstImg = np.zeros((height,width,1),np.uint8)\n",
    "# 因为卷积计算的矩阵为3*3 所以边缘要-2防止溢出\n",
    "for i in range(0,height-2):\n",
    "    for j in range(0,width-2):\n",
    "        # 进行卷积运算(中间为0的部分省略)\n",
    "        yGradient = gray[i,j]*1+gray[i,j+1]*2+gray[i,j+2]*1-gray[i+2,j]*1-gray[i+2,j+1]*2-gray[i+2,j+2]*1\n",
    "        xGradient = gray[i,j]+gray[i+1,j]*2+gray[i+2,j]-gray[i,j+2]-gray[i+1,j+2]*2-gray[i+2,j+2]\n",
    "        gradient = math.sqrt(yGradient*yGradient+xGradient*xGradient)\n",
    "        if gradient > 50:\n",
    "            dstImg[i,j] = 255\n",
    "        else:\n",
    "            dstImg[i,j] = 0\n",
    "cv2.imshow('dstImg',dstImg)\n",
    "cv2.waitKey(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
